<template>
  <div class="app-container">
    <!-- 外协项目弹窗 -->
    <el-dialog :title="titleWX" :visible.sync="openWX" width="780px" append-to-body @close="closeWX">
      <el-form ref="formWX" :model="formWX" :rules="rulesWX" label-width="100px" :inline="true">
        <el-row>
          <el-col style="height: 55px;">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="formWX.projectNo" style="width:250px" placeholder="请输入项目编号" :disabled="ReadOnly" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="formWX.projectName" style="width:250px" placeholder="请输入项目名称" :disabled="ReadOnly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="height: 55px;">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="formWX.supplierName" placeholder="请点击选择供应商" style="width:250px" :maxlength="10"
                :disabled="ReadOnly" @focus="enterprise" />
            </el-form-item>
            <el-form-item label="项目类别" prop="projectType">
              <el-select v-model="formWX.projectType" placeholder="请选择项目类别" :disabled="true" style="width:250px">
                <el-option value="自建">自建</el-option>
                <el-option value="外协">外协</el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="客户名称" prop="enterpriseName">
              <el-input v-model="formWX.enterpriseName" placeholder="请输入客户名称" style="width:250px" :maxlength="10" :disabled="ReadOnly"/>
            </el-form-item> -->
          </el-col>
        </el-row>
        <el-row>
          <el-col style="height: 55px;">
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker clearable v-model="formWX.planStartTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择计划开始时间" style="width: 250px" :disabled="ReadOnly">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="计划完成时间" prop="planCompleTime">
              <el-date-picker clearable v-model="formWX.planCompleTime" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择计划完成时间" style="width: 250px" :disabled="ReadOnly">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="height: 55px;">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formWX.status" placeholder="请选择状态" style="width:250px" :disabled="true">
                <el-option v-for="dict in dict.type.project_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目负责人" prop="projectHead">
              <el-input v-model="formWX.projectHead" style="width:250px" placeholder="请输入项目负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :disabled="ReadOnly" style="width:610px" :maxlength="3000"
                placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormWX">保 存</el-button>
        <el-button @click="cancelWX">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- ********************************************************************************************************* -->
    <el-dialog title="供应商选择" :visible.sync="openSupplier" width="800px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-form :model="queryEnterpriseParams" ref="queryFormEnterprise" size="small" :inline="true"
            v-show="showSearch" label-width="100px">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryEnterpriseParams.enterpriseName" placeholder="请输入企业名称" clearable
                @keyup.enter.native="handleQueryEnterprise" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryEnterprise">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryEnterprise">重置</el-button>
              <el-button type="primary" size="mini" @click="saveSelectEnterprise">确定</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="tableEnterprise" v-loading="loading" style="width: 100%"
            @selection-change="handleSelectionChangeEnterprise" :data="supplierList">
            <el-table-column type="selection" width="45" align="center" />
            <el-table-column label="企业名称" align="center" prop="enterpriseName" />
            <el-table-column label="联系人" align="center" prop="contacts" />
            <el-table-column label="联系电话" align="center" prop="telephone" show-overflow-tooltip="true" />
          </el-table>
          <pagination v-show="total1 > 0" :total="total1" :page.sync="queryEnterpriseParams.pageNum"
            :limit.sync="queryEnterpriseParams.pageSize" @pagination="getEnterpriseList" />
        </el-col>
      </el-row>
    </el-dialog>
    <!-- *************************************************************************************************************************************** -->
  </div>
</template>

<script>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/project/selfRecord";
import { listInfoType, listInfo } from "@/api/supplier/supplier";
import { addProject, delProject, getProject, listProject, updateClass, updateProject } from "@/api/project/self";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FileView from "@/components/FileView/index"
import Record from "./record.vue"
export default {
  name: "Project",
  components: { Treeselect, FileView, Record },
  dicts: ['self_project_status', 'project_status'],
  data() {
    var supplierName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('供应商不能为空'));
      }
      return callback()
    };
    return {
      openSupplier: false,
      titleLL: "",
      openLL: false,
      queryParamsRecord: {
        pageNum: 1,
        pageSize: 15,
      },
      queryEnterpriseParams: {
        pageNum: 1,
        pageSize: 5,
        enterpriseOrgId: null,
        enterpriseName: null,
        industry: null,
        industryType: null,
        belongTo: null,
      },
      // 表单参数
      formLL: {

      },
      // 表单校验
      rulesLL: {
        content: [{ required: true, message: '请输入更进内容', trigger: 'blur' }],
      },
      recordOpen: false,
      isShow: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自建项目表格数据
      projectList: [],
      addSign: 0,
      ReadOnly: false,
      title: "",
      open: false,
      titleWX: "添加外协项目",
      openWX: true,
      titleJF: "自建项目交付",
      openJF: false,
      typeCode: 'self',
      uploadCode: 'self',
      uploadCodeJF: 'self_delivery',
      uploadCodeLL: 'self_record',
      enterIds: [],
      //主分类
      options: null,
      showUpload: false,
      projectIds: [],
      typeSelf: 0,
      classOpen: false,
      classificationIds: '650c44e1-b575-4b62-9d54-1ba9d1e8abb7',
      projectIdLL: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        projectName: null,
        status: null,
        initStartDate: null,
        endStartDate: null,
        initCompleDate: null,
        endCompleDate: null
      },
      // 表单参数
      form: {},
      formWX: {
        projectType: "外协",
        status: "7"
      },
      formJF: {},
      totalRecord: 0,
      // 自建项目履历表格数据
      recordList: [],
      supplierList: [],
      eIds: [],
      eName: [],
      // 表单校验
      rules: {
        projectNo: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        enterpriseName: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
        projectHead: [{ required: true, message: '请输入项目负责人', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        projectType: [{ required: true, message: '请选择项目类别', trigger: 'change' }],
        planStartTime: [
          { required: true, message: '请选择计划开始时间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const planCompleTime = this.form.planCompleTime;
              if (value && planCompleTime && value > planCompleTime) {
                callback(new Error('计划开始时间不能大于计划完成时间'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        planCompleTime: [
          { required: true, message: '请选择计划完成时间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const planStartTime = this.form.planStartTime;
              if (value && planStartTime && value < planStartTime) {
                callback(new Error('计划完成时间不能小于计划开始时间'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        fee: [{ required: true, message: '请输入费用', trigger: 'blur' }],
        // ... other rules
      },
      // 表单校验
      rulesWX: {
        projectNo: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
        projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        planStartTime: [
          { required: true, message: '计划开始时间不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const planCompleTime = this.form.planCompleTime;
              if (value && planCompleTime && value > planCompleTime) {
                callback(new Error('计划开始时间不能大于计划完成时间'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        planCompleTime: [
          { required: true, message: '计划完成时间不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const planStartTime = this.form.planStartTime;
              if (value && planStartTime && value < planStartTime) {
                callback(new Error('计划完成时间不能小于计划开始时间'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        supplierName: [{ required: true, validator: supplierName, trigger: 'change' }],
        projectHead: [{ required: true, message: '项目负责人不能为空', trigger: 'blur' }],
      },
      // 表单校验
      rulesJF: {
        planStartTime: [
          { required: true, message: '请选择交付时间', trigger: 'blur' },
        ],
        projectAccounting: [{ required: true, message: '请输入项目核算', trigger: 'blur' }],
        projectPartner: [{ required: true, message: '请输入项目合作方', trigger: 'blur' }],
        projectAccomplish: [{ required: true, message: '请输入项目完成情况', trigger: 'blur' }],
        projectDeliveryPerson: [{ required: true, message: '请输入交付人', trigger: 'blur' }],
        // ... other rules
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    saveSelectEnterprise() {
      if (this.eIds.toString() == "" || this.eIds.toString() == null) {
        this.$modal.msgError("请先选择供应商！");
      } else {
        this.$set(this.formWX, 'supplierName', this.eName.toString())
        this.$set(this.formWX, 'supplierId', this.eIds.toString())
        this.closeSupplier()
      }
    },
    closeSupplier() {
      this.openSupplier = false
    },
    handleSelectionChangeEnterprise(selection) {
      if (selection.length > 1) {
        this.$refs.tableEnterprise.clearSelection(); // 清空所有选择
        this.$refs.tableEnterprise.toggleRowSelection(selection.pop()); // 设置选择项
      } else {
        this.eIds = selection.map(item => item.enterpriseOrgId)
        this.eName = selection.map(item => item.enterpriseName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      }
    },

    enterprise() {
      this.getEnterpriseList();
      setTimeout(() => {
        this.openSupplier = true;
      }, 300);
    },
    getEnterpriseList() {
      this.loading = true;
      this.queryEnterpriseParams.enterpriseOrgId = this.$store.state.user.info.orgId;
      this.queryEnterpriseParams.belongTo = this.$store.state.user.info.orgId;
      listInfo(this.queryEnterpriseParams).then(response => {
        this.supplierList = response.rows;
        this.total1 = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQueryEnterprise() {
      this.queryEnterpriseParams.pageNum = 1;
      this.getEnterpriseList();
    },
    /** 重置按钮操作 */
    resetQueryEnterprise() {
      this.resetForm("queryFormEnterprise");
      this.handleQueryEnterprise();
    },
    /** 新增项目履历按钮操作 */
    handleAddLL() {
      this.resetLL();
      this.openLL = true;
      this.formLL.creationName = this.$store.state.user.name,
        this.formLL.creationTime = this.parseTime(new Date(), '{y}-{m}-{d}'),
        this.titleLL = "添加自建项目履历";
    },
    /** 修改按钮操作 */
    handleUpdateLL(row) {
      this.resetLL();
      const id = row.id || this.ids
      getRecord(id).then(response => {
        this.formLL = response.data;
        this.openLL = true;
        this.titleLL = "修改自建项目履历";
      });
    },
    /** 履历提交按钮 */
    submitFormLL() {
      this.$refs["formLL"].validate(valid => {
        if (valid) {
          this.formLL.projectId = this.projectIdLL
          if (this.formLL.id != null) {
            updateRecord(this.formLL).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openLL = false;
              this.getListRecord();
            });
          } else {
            this.formLL.id = this.guid()
            addRecord(this.formLL).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openLL = false;
              this.getListRecord();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDeleteLL(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除履历编号为"' + ids + '"的数据项？').then(function () {
        return delRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 表单重置
    resetLL() {
      this.formLL = {
        id: null,
        projectId: null,
        status: null,
        content: null,
        remark: null,
        createId: null,
        creationTime: null,
        creationName: null
      };
      this.resetForm("formLL");
    },
    // 取消按钮
    cancelLL() {
      this.openLL = false;
      this.resetLL();
      this.getListRecord();
    },
    /** 查询自建项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getFile(data) {
      console.log(JSON.stringify(data))
    },

    handleLL(row) {
      this.recordOpen = true
      this.projectIdLL = row.projectId
      this.queryParamsRecord.projectId = row.projectId
      this.getListRecord();
    },
    /** 查询自建项目履历列表 */
    getListRecord() {
      this.loading = true;
      this.queryParamsRecord.projectId = this.projectIdLL
      listRecord(this.queryParamsRecord).then(response => {
        this.recordList = response.rows;
        this.totalRecord = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.showUpload = false;
      this.typeSelf = 0;
      this.addSign = 0;
      this.reset();
    },
    // 取消按钮
    cancelWX() {
      this.$emit('change');
    },
    //关闭对话框
    closeWX(){
      this.$emit('change');
    },
    // 取消按钮
    cancelJF() {
      this.openJF = false;
      this.addSign = 0;
      this.reset();
    },

    // 表单重置
    reset() {
      this.formWX = {
        projectId: null,
        projectNo: null,
        projectName: null,
        enterpriseName: null,
        projectHead: null,
        planStartTime: null,
        planCompleTime: null,
        status: null,
        supplierId: null,
        supplierName: null,
        createId: null,
        createName: null,
        createTime: null,
        remark: null,
        fileUpload: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        classificationId: null,
        belongTo: null
      };
      this.resetForm("form");
    },
    closeDig() {
      this.showUpload = false;
      this.typeSelf = 0;
      this.open = false;
      this.ReadOnly = false;
      this.getList();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.initStartDate = null;
      this.queryParams.endCompleDate = null;
      this.queryParams.endStartDate = null;
      this.queryParams.initCompleDate = null;
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增自建项目按钮操作 */
    handleAddZJ() {
      this.reset();
      this.ReadOnly = false
      this.form.projectType = '自建'
      this.form.status = '0'
      this.form.fileUpload = new Date().getTime();
      this.addSign = 0;
      this.typeSelf = 0;
      this.showUpload = true;
      this.open = true;
      this.title = "添加自建项目";
    },
    /** 新增自建项目按钮操作 */
    handleAddWX() {
      this.reset();
      this.ReadOnly = false
      this.formWX.projectType = '外协'
      this.formWX.status = '7'
      this.addSign = 0;
      this.openWX = true;
    },
    //序号展示
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },

    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.reset();
      this.ReadOnly = false
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.addSign = 1;
        this.typeSelf = 1;
        this.showUpload = true;
        this.form.index = index + 1;
        this.title = "修改自建项目";
      });
    },
    /** 交付按钮操作 */
    handleJF(row, index) {
      this.reset();
      const projectId = row.projectId || this.ids
      getProject(projectId).then(response => {
        this.formJF = response.data;
        this.openJF = true;
        this.addSign = 1;
        this.typeSelf = 1;
        this.showUpload = true;
        this.formJF.index = index + 1;
        this.title = "自建项目交付";
      });
    },
    //项目名称点击查询
    handleSelect(project, index) {
      this.reset();
      getProject(project).then(response => {
        this.form = response.data;
        this.ReadOnly = true;
        this.open = true;
        this.addSign = 1;
        this.typeSelf = 2;
        this.showUpload = true;
        this.form.index = index + 1;
        this.title = "查看自建项目";
      });
    },

    /** 提交按钮 */
    submitFormJF() {
      this.$refs["formJF"].validate(valid => {
        if (valid) {
          this.$modal.confirm('交付成功后项目为已完成状态，只能查看不允许修改，是否确认继续交付？').then(function () {
          }).then(() => {
            this.formJF.projectType = '自建'
            this.formJF.status = '1'
            updateProject(this.formJF).then(response => {
              this.$modal.msgSuccess("交付成功");
              this.openJF = false;
              this.getList();
            });
          }).catch(() => { });

        }
      });
    },

    /** 提交按钮 */
    submitFormWX() {
      this.$refs["formWX"].validate(valid => {
        if (valid) {
          this.$confirm('此操作会发送项目信息给指定供应商，等待供应商接收，是否继续？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.formWX.projectId != null) {
              updateProject(this.formWX).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.cancelWX();
                this.getList();
              });
            } else {
              addProject(this.formWX).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.cancelWX();
                this.getList();
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消保存'
            });
          });
        }
      });
    },
    /** 终止按钮 */
    handleZZ(row) {
      this.form.projectId = row.projectId
      this.form.projectType = '自建'
      this.form.status = '2'
      this.$modal.confirm('终止后此项目作废不能再修改，是否确认终止项目名称为"' + row.projectName + '"的数据项？').then(function () {
      }).then(() => {
        updateProject(this.form).then(response => {
          this.getList();
          this.$modal.msgSuccess("终止成功");
        });

      }).catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除自建项目编号为"' + row.projectName + '"的数据项？').then(function () {
        return delProject(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>
<style scoped>
.hyperlink {
  color: #007BFF;
  /* 蓝色 */
  text-decoration: underline;
  cursor: pointer;
}

::v-deep .el-table .el-table__header-wrapper .el-checkbox {
  display: none;
}

::v-deep .el-dialog__header {
  padding-top: 5px;
}
</style>
